<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Builder;
use Laravel\Lumen\Auth\Authorizable;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Administrator extends Base implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
    use Authenticatable, Authorizable, HasRoles, LogsActivity;

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];

    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope('status', function (Builder $builder) {
            $builder->where('status', self::STATUS_NORMAL);
        });
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    /**
     * 自定义操作日志 说明
     * @param $eventName
     * @return string
     */
    public function getDescriptionForEvent(string $eventName): string
    {
        if (!in_array($eventName, ['created', 'updated', 'deleted'])) {
            return $eventName;
        }

        switch ($eventName) {
            case 'created':
                return '创建后台管理账号:' . ($this['account'] ?? '');
            case 'updated':
                $fieldMap = [
                    'account' => [
                        'title' => '账号',
                    ],
                    'real_name' => [
                        'title' => '姓名',
                    ],
                    'phone' => [
                        'title' => '手机号'
                    ],
                    'password' => [
                        'title' => '密码'
                    ],
                    'status' => [
                        'title' => '状态',
                        'casts' => [
                            Role::STATUS_NORMAL => '启用',
                            Role::STATUS_DISABLE => '禁用',
                        ]
                    ]
                ];
                $changes = [];
                foreach ($this->getChanges() as $field => $change) {
                    if (!isset($fieldMap[$field])) {
                        continue;
                    }

                    $changes[] = $fieldMap[$field]['title'] . '变更为' . (isset($fieldMap[$field]['casts']) ? $fieldMap[$field]['casts'][$change] : $change);
                }
                return '编辑后台管理账号:' . $this->getOriginal('account') . '; 变更内容:' . implode(',', $changes);
            case 'deleted':
                return '删除后台管理账号:' . ($this['account'] ?? '');
            default:
                return $eventName;
        }
    }
}
